package com.project.shangqi.controller;

import com.alibaba.fastjson.JSON;
import com.project.shangqi.dto.*;
import com.project.shangqi.entity.VehicleColumn;
import com.project.shangqi.entity.VehicleFiber;
import com.project.shangqi.entity.VehicleInfo;
import com.project.shangqi.service.LoginService;
import com.project.shangqi.service.VehicleColumnService;
import com.project.shangqi.service.VehicleFiberService;
import com.project.shangqi.service.VehicleInfoService;
import com.project.shangqi.util.RestResult;
import org.springframework.beans.BeanUtils;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.net.URLEncoder;
import java.util.List;
import java.util.stream.Collectors;

@RestController
@RequestMapping("shangqi/api/")
public class ShangqiController {

    @Resource
    ConfigDto configDto;

    @Resource
    LoginService loginService;
    @Resource
    VehicleInfoService vehicleInfoService;
    @Resource
    VehicleFiberService vehicleFiberService;
    @Resource
    VehicleColumnService vehicleColumnService;

    @PostMapping("doLogin")
    public RestResult setStationLightingParams() {
        LoginResult result = null;
        try {
            LoginParam param = new LoginParam();
            param.setClient_id(configDto.getClient_id());
            param.setClient_secret(configDto.getClient_secret());
            param.setGrant_type(configDto.getGrant_type());
            param.setScope(configDto.getScope());
            param.setUsername(configDto.getUsername());
            param.setPassword(configDto.getPassword());
            String url = configDto.getHost() + "oauth/token";
            result = loginService.doLogin(param, url, configDto.getTimeout());
        } catch (Exception e) {
            return RestResult.error(e.getMessage());
        }
        return RestResult.ok(result);
    }

    @GetMapping("getByVin")
    public RestResult getByVin(@RequestHeader(value = "Authorization") String token, String vin) {
        VehicleResult result = null;
        try {
            String url = configDto.getHost() + "bigger/vehicle/info?q=" + vin;
            result = vehicleInfoService.getFromUrl(token, url, configDto.getTimeout());
        } catch (Exception e) {
            return RestResult.error(e.getMessage());
        }
        return RestResult.ok(result);
    }

    @GetMapping("getByFiber")
    public RestResult getByFiber(@RequestHeader(value = "Authorization") String token, String unid) {
        FiberResult result = null;
        try {
            String url = configDto.getHost() + "bigger/fiber/" + unid;
            result = vehicleFiberService.getFromUrl(token, url, configDto.getTimeout());
        } catch (Exception e) {
            return RestResult.error(e.getMessage());
        }
        return RestResult.ok(result);
    }

    @PostMapping("getByUnid/{unid}")
    public RestResult getByUnid(@RequestHeader(value = "Authorization") String token, @PathVariable("unid") String unid, @RequestBody FiberColumn column) {
        List<UnidResult> result = null;
        try {
            List<String> codeList = column.getColumns().stream().map(Column::getCode).collect(Collectors.toList());
            String code = String.join(",", codeList);
            code = URLEncoder.encode(code);
            String url = configDto.getHost() + "sensor/vehicle/" + unid + "?field=" + code;
            result = vehicleColumnService.getFromUrl(token, url, configDto.getTimeout());
        } catch (Exception e) {
            return RestResult.error(e.getMessage());
        }
        return RestResult.ok(result);
    }

    @GetMapping("getInfo")
    public RestResult getInfo(String vin) {
        LoginResult result = null;
        try {
            LoginParam param = new LoginParam();
            param.setClient_id(configDto.getClient_id());
            param.setClient_secret(configDto.getClient_secret());
            param.setGrant_type(configDto.getGrant_type());
            param.setScope(configDto.getScope());
            param.setUsername(configDto.getUsername());
            param.setPassword(configDto.getPassword());
            String url = configDto.getHost() + "oauth/token";
            result = loginService.doLogin(param, url, configDto.getTimeout());
            Long expire = System.currentTimeMillis() - result.getCurrent();
            if (result.getExpires_in().compareTo(expire) == -1) {
                loginService.clearToken();
                result = loginService.doLogin(param, url, configDto.getTimeout());
            }
            String url2 = configDto.getHost() + "bigger/vehicle/info?q=" + vin;
            VehicleResult vehicleResult = vehicleInfoService.getFromUrl(result.getAccess_token(), url2, configDto.getTimeout());
            VehicleInfo vehicleInfo = new VehicleInfo();
            BeanUtils.copyProperties(vehicleResult, vehicleInfo);
            vehicleInfo.setSnapshot(JSON.toJSONString(vehicleResult.getSnapshot()));
            vehicleInfoService.insert(vehicleInfo);

            String url3 = configDto.getHost() + "bigger/fiber/" + vehicleInfo.getFiber_unid();
            FiberResult fiberResult = vehicleFiberService.getFromUrl(result.getAccess_token(), url3, configDto.getTimeout());
            VehicleFiber vehicleFiber = new VehicleFiber();
            BeanUtils.copyProperties(fiberResult, vehicleFiber);
            vehicleFiber.setColumn_group(JSON.toJSONString(fiberResult.getColumn_group()));
            vehicleFiberService.insert(vehicleFiber);

            List<String> codeList = fiberResult.getColumn_group().getColumns().stream().map(Column::getCode).collect(Collectors.toList());
            String code = String.join(",", codeList);
            code = URLEncoder.encode(code);
            String url4 = configDto.getHost() + "sensor/vehicle/" +  vehicleInfo.getUnid() + "?field=" + code;
            List<UnidResult> unidResult = vehicleColumnService.getFromUrl(result.getAccess_token(), url4, configDto.getTimeout());
            VehicleColumn vehicleColumn = new VehicleColumn();
            vehicleColumn.setColumns(JSON.toJSONString(unidResult));
            vehicleColumnService.insert(vehicleColumn);

        } catch (Exception e) {
            return RestResult.error(e.getMessage());
        }
        return RestResult.ok();
    }
}
